package com.zerocarbon.framework.common.utils;

import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * RSA加解密工具类
 * @author wyf
 * @date 2020年3月5日
 */
@Slf4j
public class RsaUtils {
	
    /**
     * 默认"RSA"="RSA/ECB/PKCS1Padding"
     */
    private static final String CIPHER_INSTANCE = "RSA/ECB/PKCS1Padding";
    private static final String RSA_ALGORITHM = "RSA";
    private static final String SIGNATURE_ALGORITHM = "SHA1withRSA";

    //private static final int MAX_ENCRYPT_BLOCK = 117; //RSA最大加密明文大小
    //private static final int MAX_DECRYPT_BLOCK = 128; //RSA最大解密密文大小
    
    private static final String CHARSET = "UTF-8";
    
    /*************************公钥加密，私钥解密 begin*******************************/
    /**
     * 公钥加密
     * @param content 要加密的内容
     * @param publicKey 公钥
     */
    public static String encrypt(String content, RSAPublicKey publicKey) {
        try{
            byte[] output = rsaSplitCodec(getEncryptCipher(publicKey), Cipher.ENCRYPT_MODE, content.getBytes(CHARSET), publicKey.getModulus().bitLength());
            return Base64.getEncoder().encodeToString(output);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Cipher getEncryptCipher(PublicKey publicKey) throws Exception  {
    	 Cipher cipher = Cipher.getInstance(CIPHER_INSTANCE);
         cipher.init(Cipher.ENCRYPT_MODE, publicKey);
		return cipher;
    }

    /**
     * 私钥解密
     * @param content 要解密的内容
     * @param privateKey 私钥
     */
    public static String decrypt(String content, RSAPrivateKey privateKey) {
        try {
            byte [] b = rsaSplitCodec(getDecryptCipher(privateKey), Cipher.DECRYPT_MODE, Base64.getDecoder().decode(content), privateKey.getModulus().bitLength());
            return new String(b, CHARSET);
        } catch (Exception e){
            log.error("私钥解密解密异常", e);
        }
        return null;
    }
    
    public static Cipher getDecryptCipher(PrivateKey privateKey) throws Exception  {
    	Cipher cipher = Cipher.getInstance(CIPHER_INSTANCE);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher;
    }
    /*************************公钥加密，私钥解密 end*******************************/
    
    /*************************私钥加密，公钥解密 begin*******************************/
    /**
     * 私钥加密
     * @param content 要加密的内容
     * @param publicKey 公钥
     */
    public static String encrypt(String content, RSAPrivateKey privateKey) {
        try{
            byte[] output = rsaSplitCodec(getEncryptCipher(privateKey), Cipher.ENCRYPT_MODE, content.getBytes(CHARSET), privateKey.getModulus().bitLength());
            return Base64.getEncoder().encodeToString(output);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Cipher getEncryptCipher(RSAPrivateKey privateKey) throws Exception  {
    	 Cipher cipher = Cipher.getInstance(CIPHER_INSTANCE);
         cipher.init(Cipher.ENCRYPT_MODE, privateKey);
		return cipher;
    }

    /**
     * 公钥解密
     * @param content 要解密的内容
     * @param privateKey 私钥
     */
    public static String decrypt(String content, RSAPublicKey publicKey) {
        try {
            byte [] b = rsaSplitCodec(getDecryptCipher(publicKey), Cipher.DECRYPT_MODE, Base64.getDecoder().decode(content), publicKey.getModulus().bitLength());
            return new String(b, CHARSET);
        } catch (Exception e){
        	log.error("公钥解密解密异常", e);
        }
        return null;
    }
    
    public static Cipher getDecryptCipher(RSAPublicKey publicKey) throws Exception  {
    	Cipher cipher = Cipher.getInstance(CIPHER_INSTANCE);
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        return cipher;
    }
    /*************************私钥加密，公钥解密 end*******************************/
    
    
    /**
     * 获取公钥
     * @param publicKeyBase64
     * @return
     * @throws Exception
     */
    public static PublicKey getPublicKey(String publicKeyBase64) {
        String pem = publicKeyBase64.replaceAll("\\-*BEGIN PUBLIC KEY\\-*", "").replaceAll("\\-*END PUBLIC KEY\\-*", "").trim();
        PublicKey publicKey = null;
		try {
	        X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(pem));
			KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
			publicKey = keyFactory.generatePublic(pubKeySpec);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (InvalidKeySpecException e) {
			e.printStackTrace();
		}
        return publicKey;
    }

    /**
     * 获取公钥
     * @param publicKeyBase64
     * @return
     */
    public static RSAPublicKey getRSAPublicKey(String publicKeyBase64) {
        return (RSAPublicKey)getPublicKey(publicKeyBase64);
    }

    /**
     * String转私钥PrivateKey
     * @param key 私钥字符
     */
    public static PrivateKey getPrivateKey(String privateKeyBase64) {
    	String pem = privateKeyBase64.replaceAll("\\-*BEGIN PRIVATE KEY\\-*", "").replaceAll("\\-*END PRIVATE KEY\\-*", "").trim();
        KeyFactory keyFactory;
		try {
	        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(pem));
			keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
			return keyFactory.generatePrivate(keySpec);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (InvalidKeySpecException e) {
			e.printStackTrace();
		}
        return null;
    }
    
    /**
     * 获取私钥
     * @param publicKeyBase64
     * @return
     */
    public static RSAPrivateKey getRSAPrivateKey(String publicKeyBase64) {
        return (RSAPrivateKey)getPrivateKey(publicKeyBase64);
    }
    
    public static byte[] rsaSplitCodec(Cipher cipher, int opmode, byte[] datas, int keySize) throws IOException {
        int maxBlock = 0;
        if(opmode == Cipher.DECRYPT_MODE){
            maxBlock = keySize / 8;
        	//maxBlock = MAX_DECRYPT_BLOCK;
        } else {
            maxBlock = keySize / 8 - 11;
        	//maxBlock = MAX_ENCRYPT_BLOCK;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] buff;
        int i = 0;
        try{
            while(datas.length > offSet){
                if(datas.length-offSet > maxBlock){
                    buff = cipher.doFinal(datas, offSet, maxBlock);
                }else{
                    buff = cipher.doFinal(datas, offSet, datas.length-offSet);
                }
                out.write(buff, 0, buff.length);
                i++;
                offSet = i * maxBlock;
            }
        } catch(Exception e){
            throw new RuntimeException("加解密阀值为["+maxBlock+"]的数据时发生异常", e);
        }
        byte[] resultDatas = out.toByteArray();
        out.close();
        return resultDatas;
    }
    
    /**
     * 用私钥对信息生成数字签名
     * @param data			已加密数据
     * @param privateKey	私钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static String sign(byte[] data, RSAPrivateKey privateKey) {
        Signature signature;
		try {
			signature = Signature.getInstance(SIGNATURE_ALGORITHM);
			signature.initSign(privateKey);
			signature.update(data);
	        return Base64.getEncoder().encodeToString(signature.sign());
		} catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
			e.printStackTrace();
			return null;
		}
    }
    
    /**
     * 校验数字签名
     * @param data		已加密数据
     * @param publicKey 公钥(BASE64编码)
     * @param sign		数字签名
     * @return
     * @throws Exception
     */
    public static boolean verify(byte[] data, RSAPublicKey publicKey, String sign) {
        Signature signature;
		try {
			signature = Signature.getInstance(SIGNATURE_ALGORITHM);
			signature.initVerify(publicKey);
	        signature.update(data);
	        return signature.verify(Base64.getDecoder().decode(sign));
		} catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
			e.printStackTrace();
			return false;
		}
    }
    
    /*public static void main(String arg[]) {
    	String sign = encrypt("评估-cc@#@$@@#$~!@!@!#$%@$#^#$^&%&-+,c", getRSAPrivateKey(privateKey));
    	System.out.println(sign);
    	String text = decrypt(sign, getRSAPublicKey(publicKey));
    	System.out.println(text);
    }*/
}
